﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Xrm.Client;
using System.Collections;
using CRMHelpers;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk;

namespace ExcelToDynamicsCRM
{
    public partial class SearchForm : Form
    {
        String CurrentEntitieName;
        DataGridViewCell CurrentCell;
        DataGridView CurrentDataGridView;
        CrmOrganizationServiceContext crmContext;
        Hashtable EntityMetadataAttributesListinExcelPackage = new Hashtable();
        Hashtable EntityMetadataRelationShipListinExcelPackage = new Hashtable();
        Hashtable EntityColumnsListinExcelPackage = new Hashtable();
        LabelHelper lbhelp;
        EntityHelper ethelp;
        String crmurl;
        public SearchForm()
        {
            InitializeComponent();
        }

        public SearchForm(String _CurrentEntitieName, DataGridView _CurrentDataGridView, DataGridViewCell _CurrentCell, String _CurrentValue,
             CrmOrganizationServiceContext _crmContext, Hashtable _EntityMetadataAttributesListinExcelPackage, Hashtable _EntityMetadataRelationShipListinExcelPackage, 
            Hashtable _EntityColumnsListinExcelPackage,  LabelHelper _lbhelp, EntityHelper _ethelp, String _crmurl)
        {
            InitializeComponent();
            this.CurrentEntitieName = _CurrentEntitieName;
            this.CurrentCell = _CurrentCell;
            this.CurrentDataGridView = _CurrentDataGridView;
            this.crmContext = _crmContext;
            this.EntityMetadataAttributesListinExcelPackage = _EntityMetadataAttributesListinExcelPackage;
            this.EntityMetadataRelationShipListinExcelPackage = _EntityMetadataRelationShipListinExcelPackage;
            this.EntityColumnsListinExcelPackage = _EntityColumnsListinExcelPackage;
            this.lbhelp = _lbhelp;
            this.ethelp = _ethelp;
            this.crmurl = _crmurl;
            
            
            this.setDataGridView();

            
        }


        protected void setDataGridView()
        {
            if (EntityMetadataRelationShipListinExcelPackage.ContainsKey(CurrentEntitieName))
            {
                TabPage tb = new TabPage(CurrentCell.OwningColumn.Name);
                tb.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
                this.tabControl.TabPages.Add(tb);
                DataGridView dataGridViewPossibleValue = new DataGridView();

                dataGridViewPossibleValue = new DataGridView();
                dataGridViewPossibleValue.AllowUserToAddRows = false;
                dataGridViewPossibleValue.AllowDrop = false;
                dataGridViewPossibleValue.AllowUserToDeleteRows = false;
                dataGridViewPossibleValue.AllowUserToOrderColumns = false;
                dataGridViewPossibleValue.AllowUserToResizeColumns = true;
                dataGridViewPossibleValue.AllowUserToResizeRows = true;
                dataGridViewPossibleValue.EnableHeadersVisualStyles = false;
                dataGridViewPossibleValue.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders;
                dataGridViewPossibleValue.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
                dataGridViewPossibleValue.ReadOnly = true;
                dataGridViewPossibleValue.MultiSelect = false;

                dataGridViewPossibleValue.CellDoubleClick += new DataGridViewCellEventHandler(dataGridView_CellDoubleClick);


                EntityMetadata currentEntity = (EntityMetadata)EntityMetadataRelationShipListinExcelPackage[CurrentEntitieName];

                Hashtable columns = (Hashtable)EntityColumnsListinExcelPackage[CurrentEntitieName];
                if (columns.ContainsKey(CurrentCell.OwningColumn.Name))
                {

                    AttributeMetadata Attributecolumn = ethelp.getAttribute(currentEntity.LogicalName, ((AttributeMetadata)columns[CurrentCell.OwningColumn.Name]).LogicalName);
                    if (Attributecolumn.AttributeType == AttributeTypeCode.Picklist )
                    {
                        dataGridViewPossibleValue.Columns.Add("value", "Value");
                        PicklistAttributeMetadata picklistvalues = ethelp.GetPicklistofField(currentEntity.LogicalName, ((AttributeMetadata)columns[CurrentCell.OwningColumn.Name]).LogicalName);
                        foreach (OptionMetadata po in picklistvalues.OptionSet.Options)
                        {
                            object[] values = new object[1];
                            values[0] = po.Label.UserLocalizedLabel.Label;
                            dataGridViewPossibleValue.Rows.Add(values);
                        }
                    }

                    if ( Attributecolumn.AttributeType == AttributeTypeCode.Boolean)
                    {
                        dataGridViewPossibleValue.Columns.Add("value", "Value");
                        BooleanAttributeMetadata picklistvalues = ethelp.GetBooleanlistofField(currentEntity.LogicalName, ((AttributeMetadata)columns[CurrentCell.OwningColumn.Name]).LogicalName);
                        
                            object[] values = new object[1];
                            values[0] = picklistvalues.OptionSet.TrueOption.Label.UserLocalizedLabel.Label;
                            object[] values2 = new object[1];
                            values2[0] = picklistvalues.OptionSet.FalseOption.Label.UserLocalizedLabel.Label;
                            dataGridViewPossibleValue.Rows.Add(values);
                            dataGridViewPossibleValue.Rows.Add(values2);
                        
                    }
                    if (Attributecolumn.AttributeType == AttributeTypeCode.Status)
                    {
                        dataGridViewPossibleValue.Columns.Add("value", "Value");
                        StatusAttributeMetadata statusvalues = ethelp.GetStatustofField(currentEntity.LogicalName, ((AttributeMetadata)columns[CurrentCell.OwningColumn.Name]).LogicalName);
                        foreach (OptionMetadata po in statusvalues.OptionSet.Options)
                        {
                            object[] values = new object[1];
                            values[0] = po.Label.UserLocalizedLabel.Label;
                            dataGridViewPossibleValue.Rows.Add(values);
                        }
                    }
                    if (Attributecolumn.AttributeType == AttributeTypeCode.Customer || Attributecolumn.AttributeType == AttributeTypeCode.Owner || Attributecolumn.AttributeType == AttributeTypeCode.Lookup || Attributecolumn.AttributeType == AttributeTypeCode.PartyList)
                    {
                        dataGridViewPossibleValue.Columns.Add("ID", "ID");
                        dataGridViewPossibleValue.Columns.Add("Name", "Name");
                        dataGridViewPossibleValue.Columns.Add("Type", "Type");
                        dataGridViewPossibleValue.Columns.Add("State", "State");
                        dataGridViewPossibleValue.Columns.Add("CreatedOn","Created On");
                        dataGridViewPossibleValue.Columns.Add("Link", "Link");
                        dataGridViewPossibleValue.CellContentClick += new DataGridViewCellEventHandler(dataGridView_CellContentClick);
                        
                        List<Entity> relatedobjects = ethelp.getRelatedObject(currentEntity, ((AttributeMetadata)columns[CurrentCell.OwningColumn.Name]).LogicalName, CurrentCell.Value + "");
                        if (relatedobjects.Count > 1)
                        {
                            object[] values = new object[6];
                            foreach (Entity et in relatedobjects)
                            {
                                EntityMetadata etm = ethelp.GetEntityByLogicalName(et.LogicalName);

                                values[0] = et.GetAttributeValue(etm.PrimaryIdAttribute);
                                values[1] = et.GetAttributeValue(etm.PrimaryNameAttribute);
                                values[2] = et.LogicalName;
                                if (et.Contains("statecode"))
                                {
                                    values[3] = lbhelp.GetValueofStateInDefaultLanguage(et.LogicalName, "statecode", et.GetAttributeValue<OptionSetValue>("statecode").Value);
                                }
                                values[4] = et.GetAttributeValue("createdon");
                                Uri directlink = new Uri(crmurl + "/main.aspx?etn=" + et.LogicalName + "&id=%7b" + et.GetAttributeValue(etm.PrimaryIdAttribute) + "%7d&rof=false&pagetype=entityrecord");
                                values[5] = directlink;
                                dataGridViewPossibleValue.Rows.Add(values);
                            }
                        }
                    }
                }



                tb.Controls.Add(dataGridViewPossibleValue);

                Size tempSize = dataGridViewPossibleValue.Size;

                // Set the Width.
                tempSize.Width = dataGridViewPossibleValue.Parent.Size.Width;
                tempSize.Height = dataGridViewPossibleValue.Parent.Size.Height;
                // Set the size back.
                dataGridViewPossibleValue.Size = tempSize;
            }

        }

         private void dataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView CurrentdataGridView = (DataGridView)(sender as Control);
            foreach (TabPage t in this.tabControl.TabPages)
            {
                foreach (DataGridView w in t.Controls.OfType<DataGridView>())
                {

                    if (w.Rows != null && w.Rows.Count > 1)
                        this.CurrentCell.Value = w.Rows[w.CurrentRow.Index].Cells[0].Value;



                }
            }


            this.FindForm().Close();

             
         }
        private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView CurrentdataGridView = (DataGridView)(sender as Control);

            // Open the link in the default browser

            try
            {
                Uri directlinktoentity = new Uri(CurrentdataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
                System.Diagnostics.Process.Start(directlinktoentity.AbsoluteUri);



            }
            catch
            {


            }
        }
        private void button1_Click(object sender, EventArgs e)
        {

            foreach (TabPage t in this.tabControl.TabPages)
            {
                foreach (DataGridView w in t.Controls.OfType<DataGridView>())
                {

                   if(w.Rows != null && w.Rows.Count > 1)
                        this.CurrentCell.Value = w.Rows[w.CurrentRow.Index].Cells[0].Value;
                    


                }
            }
           

            this.FindForm().Close();
        }
    }
}
